<template>
  <div class="view-box info-box">
    <info-title :title="infoTitle" icon="el-icon-s-custom"></info-title>
    <div class="info-content">
      <div style="width: 50%; margin: 10px auto">
        <el-form ref="form" :model="form" label-width="80px" :rules="rules">
          <el-form-item label="角色名称" prop="name">
            <el-input class="info-text" v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="角色描述">
            <el-input class="info-text" v-model="form.desc"></el-input>
          </el-form-item>
          <el-form-item label="状态" v-show="type == 'update'">
            <el-switch
              v-model="form.status"
              :active-value="'0'"
              :inactive-value="'1'"
            ></el-switch>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-check"
              @click="onSubmit('form')"
              >确定</el-button
            >
            <el-button icon="el-icon-back" @click="$router.go(-1)"
              >返回</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
// 导入标题组件
import infoTitle from "../../../../components/common/info-title";
import { addRole, updateRole } from "../../../../api/role";
export default {
  data() {
    return {
      // 标题信息
      infoTitle: "新增角色",
      //   表单信息
      form: {
        name: "",
        desc: "",
        status: "",
      },
      //   当前是修改还是新增
      type: "add",
      // 表单信息校验
      rules: {
        name: [
          { required: true, message: "角色名称不能为空", trigger: "blur" },
        ],
      },
    };
  },
  components: { infoTitle },
  mounted() {
    if (JSON.stringify(this.$route.params) != "{}") {
      this.form = this.$route.params;
      this.infoTitle = "修改角色";
      this.type = "update";
    }
  },
  methods: {
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitData();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    submitData() {
      if (this.type == "update") {
        updateRole(this.form).then((res) => {
          if (res.success) this.$router.go(-1);
        });
      } else {
        addRole(this.form).then((res) => {
          if (res.success) this.$router.go(-1);
        });
      }
    },
  },
};
</script>

<style scoped>
.view-box {
  padding: 10px;
}
.info-content {
  padding: 10px;
}
</style>